package cn.wit.summit.chwan.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.DetailFragmentAdapter;
import cn.wit.summit.chwan.models.dto.CommentBaseBean;
import cn.wit.summit.chwan.models.dto.GameInfoDetial;
import cn.wit.summit.chwan.models.request.AddPraiseRequest;
import cn.wit.summit.chwan.models.request.GetCommentTokenRequest;
import cn.wit.summit.chwan.models.request.GetGameCommentRequest;
import cn.wit.summit.chwan.models.response.AddPraiseResponse;
import cn.wit.summit.chwan.models.response.CommentAllListResponse;
import cn.wit.summit.chwan.models.response.GetCommentTokenResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.activity.CommentDetailActivity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.utils.AESUtils;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringToUnicodeUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DetialRecycleview;
import retrofit2.Retrofit;

/**
 * Created by yangg on 2018/4/12.
 */

public class DetailFragment extends BaseFragment implements DetailFragmentAdapter.Listener {

    @Bind(R.id.rcy_view)
    DetialRecycleview rcy;
    GameInfoDetial gameInfoDetial;
    DetailFragmentAdapter adapter;
    private boolean firstLoadData = true;
    Context mContext;
    List<DetailFragmentAdapter.GamedetialItemMain> datas;

    private RetrofitManager retrofitManager;
    private Retrofit retrofitComment;
    private ApiUtil apiComment;

    public static DetailFragment newInstance(GameInfoDetial intentData) {
        Bundle args = new Bundle();
        args.putSerializable("gameDetial", intentData);
        DetailFragment fragment = new DetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.detailfragment, null);
        ButterKnife.bind(this, view);
        mContext = getContext();

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofitComment = retrofitManager.getCommentRetrofit();
        apiComment = retrofitComment.create(ApiUtil.class);

        gameInfoDetial = (GameInfoDetial) getArguments().getSerializable("gameDetial");
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        rcy.setLayoutManager(layoutManager);
        adapter = new DetailFragmentAdapter(getActivity(), gameInfoDetial);
        adapter.setListenr(this);
        datas = adapter.getlistData();
        initData(gameInfoDetial);
        rcy.setAdapter(adapter);
        return view;
    }

    private void initData(GameInfoDetial gameInfoDetial) {
        datas.clear();
        if (gameInfoDetial.getGame_slide_pic() != null && gameInfoDetial.getGame_slide_pic().getPic_list() != null && gameInfoDetial.getGame_slide_pic().getPic_list().size() > 0)
            datas.add(adapter.new GamedetialItemMain(null, DetailFragmentAdapter.ViewType.IMAGES));
        if (gameInfoDetial.getGame_prize_ad() != null && gameInfoDetial.getGame_prize_ad().size() > 0)
            datas.add(adapter.new GamedetialItemMain(null, DetailFragmentAdapter.ViewType.ADVIEW));
        if (StringUtils.isNotEmpty(gameInfoDetial.getGame_introduce())) {
            datas.add(adapter.new GamedetialItemMain("简介:", DetailFragmentAdapter.ViewType.ITEMTITLE));
            datas.add(adapter.new GamedetialItemMain(null, DetailFragmentAdapter.ViewType.DESCRIBE));
        }
        if (gameInfoDetial == null || gameInfoDetial.getGame_comment_switch() == 1) {
            if (gameInfoDetial.getCommitDataBeanList() != null && gameInfoDetial.getCommitDataBeanList().size() > 0) {
                datas.add(adapter.new GamedetialItemMain("评论", DetailFragmentAdapter.ViewType.ITEMTITLE));
                setCommit(datas);
            } else if (firstLoadData) {//如果【】评论列表开并且没有评论那么去获取评论
                firstLoadData = false;
                getGameCommentList();
            } else {
                datas.add(adapter.new GamedetialItemMain("评论", DetailFragmentAdapter.ViewType.ITEMTITLE));
                datas.add(adapter.new GamedetialItemMain("评论", DetailFragmentAdapter.ViewType.NO_COMMIT));
//                datas.add(adapter.new GamedetialItemMain("评论", DetailFragmentAdapter.ViewType.COMMITGAME));
            }
        }
        if (StringUtils.isNotEmpty(gameInfoDetial.getGame_diagram())) {
            datas.add(adapter.new GamedetialItemMain("图解游戏", DetailFragmentAdapter.ViewType.ITEMTITLE));
            datas.add(adapter.new GamedetialItemMain("", DetailFragmentAdapter.ViewType.WEBVIEW));
        }
        adapter.notifyDataSetChanged();
    }

    private CommentBaseBean selfComment;

    public CommentBaseBean getSelfComment() {
        return selfComment;
    }

    private void setCommit(List<DetailFragmentAdapter.GamedetialItemMain> gamedetialItemMains) {
        if (gameInfoDetial == null || gameInfoDetial.getGame_comment_switch() != 1) return;
//
        int notData = 0;
        for (int i = 0; null != gameInfoDetial.getCommitDataBeanList() && i < gameInfoDetial.getCommitDataBeanList().size(); i++) {
            CommentBaseBean data = gameInfoDetial.getCommitDataBeanList().get(i);
            int uid = AccountUtil.getInstance().getUid();
            if (uid != 0 && data.getUid().equals(uid+"")) {
                selfComment = data;
            } else {
                notData += 1;
            }
            if (notData==gameInfoDetial.getCommitDataBeanList().size()) {
                selfComment = null;
            }
            String str = data.getContent();
            if (str.contains("EM-")) {
                try {
                    str = StringToUnicodeUtil.unicode2String(str);
                    data.setContent(str);
                } catch (Exception e) {
                    LogUtils.e("---m---e.getMessage():" + e.getMessage());
                }
            }
            if (i == 0)
                data.setIsfirst(true);
            gamedetialItemMains.add(adapter.new GamedetialItemMain(data, DetailFragmentAdapter.ViewType.COMMENTITEM));
//            if (i == 0) {
//                gamedetialItemMains.add(adapter.new GamedetialItemMain("", DetailFragmentAdapter.ViewType.COMMITGAME));
//            }
        }
        gamedetialItemMains.add(adapter.new GamedetialItemMain("评论底部", DetailFragmentAdapter.ViewType.COMMIT_FOOTER));
    }

    private int pn = 1;
    private int pc = 20;

    private String comentToken = "-1";
    private int uId;
    private String uToken;

    private void getCommentToken(final CommentBaseBean bean, final int position, final int type, final int i) {

        GetCommentTokenRequest tempRequest = retrofitManager.getCommentTokenRequest();
        apiComment.getCommentToken(tempRequest).enqueue(new MyCallback<ResponseBase<GetCommentTokenResponse>>() {
            @Override
            public void onSuccess(ResponseBase<GetCommentTokenResponse> model) {
                GetCommentTokenResponse data = model.getData_info();
                String token = AESUtils.encrypt4Comment(data.getToken() + "|" + data.getTimes());
                comentToken = token;
                PreferenceUtil.savePreference(getActivity(), PreferenceUtil.PRE_COMMENT_TOKEN, token);
                PreferenceUtil.saveLongPreference(getActivity(), PreferenceUtil.PRE_COMMENT_TOKEN_TIME, data.getTimes());
                if (i == 1)
                    onPraise(bean, position, type);
                else if (i == 2)
                    onUnPraise(bean, position, type);
                else if (i == 3) {
                    getGameCommentList();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, "-1");
                try {
                    showToast(msg);
                    cancelLoading();
                } catch (Exception e) {

                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!firstLoadData) {
            getGameCommentList();
        }
    }

    private void getGameCommentList() {
        firstLoadData = false;
        comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
        if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
            getCommentToken(null, 0, 0, 3);
            return;
        }
        uId = AccountUtil.getInstance().getUid();
        uToken = AccountUtil.getInstance().getToken();

        GetGameCommentRequest commentRequest = retrofitManager.getGameDetailCommentRequest(comentToken, gameInfoDetial.getGame_id(), uId);
        apiComment.getGameDetailComments(commentRequest).enqueue(new MyCallback<ResponseBase<CommentAllListResponse>>() {
            @Override
            public void onSuccess(ResponseBase<CommentAllListResponse> model) {
                CommentAllListResponse commitDataBeans = model.getData_info();
                if (commitDataBeans != null) {
                    String Game_comment_count = commitDataBeans.getGame_comment_count()+"";
                    Intent intent = new Intent("send.broadcast.game.comment.count");
                    intent.putExtra("Game_comment_count", Game_comment_count);
                    mContext.sendBroadcast(intent);

                    if (null != commitDataBeans && commitDataBeans.getHot_comment() != null && commitDataBeans.getHot_comment().size() >= 0) {

                        List<CommentBaseBean> hotCommentBean = commitDataBeans.getHot_comment();
                        gameInfoDetial.setCommitDataBeanList(hotCommentBean);

                        initData(gameInfoDetial);
                    } else {

                        gameInfoDetial.setCommitDataBeanList(null);
                        initData(gameInfoDetial);
                    }
                } else {
                    gameInfoDetial.setCommitDataBeanList(null);
                    initData(gameInfoDetial);
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    @Override
    public void onPostingClick() {

    }

    private String commentId;

    @Override
    public void onPraise(final CommentBaseBean bean, final int position, final int type) {
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
            if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
                getCommentToken(bean, position, type, 1);
                return;
            }
            uId = AccountUtil.getInstance().getUid();
            uToken = AccountUtil.getInstance().getToken();
            commentId = bean.getId();

            AddPraiseRequest tempRequest = retrofitManager.addPraiseRequest(comentToken, gameInfoDetial.getGame_id(), uId, uToken, commentId, type, pn);
            apiComment.addPraise(tempRequest).enqueue(new MyCallback<ResponseBase<AddPraiseResponse>>() {
                @Override
                public void onSuccess(ResponseBase<AddPraiseResponse> model) {
                    checkReset(position, 1);
                }

                @Override
                public void onFailure(int code, String msg) {
                    if (code==801)
                        getCommentToken(bean, position, type, 1);
                    resultShow(msg, true, position, 1);
                }
            });
        } else {
            resultShow("网络连接失败，再试试吧~", true, position, 1);
        }
    }

    public void checkReset(int position, int i) {
        if (i == 1) {
            adapter.resetDespise(position, 1);
        } else {
            adapter.resetPraise(position, 1);
        }
    }

    private void resultShow(String msg, boolean b, int position, int type) {
        showToast(msg);
        if (b) {
            if (type == 1)
                adapter.resetPraise(position, 0);
            else
                adapter.resetDespise(position, 0);
        }
    }

    @Override
    public void onUnPraise(final CommentBaseBean bean, final int position, final int type) {
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
            if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
                getCommentToken(bean, position, type, 2);
                return;
            }
            uId = AccountUtil.getInstance().getUid();
            uToken = AccountUtil.getInstance().getToken();
            commentId = bean.getId();

            AddPraiseRequest tempRequest = retrofitManager.unPraiseRequest(comentToken, gameInfoDetial.getGame_id(), uId, uToken, commentId, type, pn);
            apiComment.subPraise(tempRequest).enqueue(new MyCallback<ResponseBase<AddPraiseResponse>>() {
                @Override
                public void onSuccess(ResponseBase<AddPraiseResponse> model) {
                    checkReset(position, 2);
                }

                @Override
                public void onFailure(int code, String msg) {
                    if (code==801)
                        getCommentToken(bean, position, type, 2);
                    resultShow(msg, true, position, 2);
                }
            });
        } else {
            resultShow("网络连接失败，再试试吧~", true, position, 2);
        }
    }

    @Override
    public void onRootView(CommentBaseBean bean) {
        Intent intent = new Intent(getActivity(), CommentDetailActivity.class);
        intent.putExtra("commentId", bean.getId());
        intent.putExtra("data", bean);
        getActivity().startActivity(intent);
    }
}
